package com.jjlin.chapter_3;

import java.util.*;
public class CD166{
    //二叉树节点
    public static class Node{
        public int val;
        public Node left;
        public Node right;
        public Node(int data){
            this.val = data;
        }
    }

    //建立二叉树
    public static Node createBinaryTree(int[][] nums, int root){
        HashMap<Integer, Node> map = new HashMap<>();
        for(int i = 0; i < nums.length; ++i){
            map.putIfAbsent(nums[i][0], new Node(nums[i][0]));
            if(nums[i][1] != 0){
                map.putIfAbsent(nums[i][1], new Node(nums[i][1]));
                map.get(nums[i][0]).left = map.get(nums[i][1]);
            }
            if(nums[i][2] != 0){
                map.putIfAbsent(nums[i][2], new Node(nums[i][2]));
                map.get(nums[i][0]).right = map.get(nums[i][2]);
            }
        }
        return map.get(root);
    }

    //找到二叉树中的最大搜索二叉子树
    public static int biggestSubBST(Node root){
        if(root == null)
            return 0;
        int[] record = new int[3]; //record分别记录该节点的最大搜索子树的节点数、最小值和最大值
        Node node = posOrder(root, record);//最大搜索二叉子树的根节点
        return record[0];
    }

    public static Node posOrder(Node node, int[] record){
        if(node == null){
            record[0] = 0;
            record[1] = Integer.MAX_VALUE;
            record[2] = Integer.MIN_VALUE;
            return null;
        }
        int value = node.val;
        Node left = node.left;
        Node right = node.right;
        Node lBST = posOrder(left, record);//记录以左节点为根节点的二叉树的最大二叉搜索子树的根节点、节点数、最小值和最大值
        int lsize = record[0];
        int lmin = record[1];
        int lmax = record[2];
        Node rBST = posOrder(right, record);//记录以右节点为根节点的二叉树的最大二叉搜索子树的根节点、节点数、最小值和最大值
        int rsize = record[0];
        int rmin = record[1];
        int rmax = record[2];
        record[1] = Math.min(value, lmin);//记录最小值
        record[2] = Math.max(value, rmax);//记录最大值
        if(left == lBST && right == rBST && value > lmax && value < rmin){//node为二叉搜索子树的根节点
            record[0] = lsize + rsize + 1;//记录节点数
            return node;
        }
        record[0] = Math.max(lsize, rsize);//node不是二叉搜索子树的根节点
        return lsize > rsize ? lBST : rBST;//返回最大的二叉搜索子树
    }

    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int root = sc.nextInt();
        int[][] nums = new int[n][3];
        for(int i = 0; i < n; ++i)
            for(int j = 0; j < 3; ++j)
                nums[i][j] = sc.nextInt();
        Node head = createBinaryTree(nums, root);
        System.out.println(biggestSubBST(head));
    }
}
